﻿#region LicenseHeader

// Copyright 2012 The Trustees of Indiana University.  All rights reserved.
// 
// The Indiana University licenses this file to you under the Apache License, 
// Version 2.0 (the "License"); you may not use this file except in compliance 
// with the License.  You may obtain a copy of the License at 
// 
// http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software 
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
//  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
// See the License for the specific language governing permissions and 
// limitations under the License.
// 
// @author Thilina Gunarathne (tgunarat@indiana.edu)

#endregion

using System.Collections.Generic;
using System.IO;
using AzureMRCore;
using AzureMRCore.DataTypes;
using AzureMRCore.MapRed;

namespace SWGMBFSample
{
    internal class SWGReducer : Reducer<IntKey, FileValue, IntKey, FileValue>
    {
        public override int Reduce(IntKey key, List<FileValue> values, IOutputCollector<IntKey, FileValue> outputCollector, string programArgs)
        {
            string fileName = GetHashCode() + key.GetTextValue() + ".out";
            FileStream outFile = File.Create(fileName);
            int start = 0;
            foreach (FileValue file in values)
            {
                FileStream inFile = File.Open(file.GetTextValue(), FileMode.Open);
                byte[] content = new byte[inFile.Length];
                inFile.Read(content, 0, (int) inFile.Length);
                outFile.Write(content, 0, (int) inFile.Length);
                start += (int) inFile.Length;
                inFile.Close();
            }
            outFile.Close();

            FileValue value = new FileValue();
            value.Value = new FileInfo(fileName);
            outputCollector.Collect(key, value);
            return 0;
        }
    }
}